<?php


namespace Application\controller;

class LoginController extends BaseLoginController
{
    protected $config_fields = ['config'];

    public function login()
    {
        // 初始化参数
        $m = $this->initLogin();
        if (empty($m->account)) $this->error($m->msg);
        $struct = $m->lastStruct();
        // 检测白名单
        $whitelist = $this->isWhitelist($m->account, $m->deviceCode);
        // 初始化区服条件
        $this->initServerMap($whitelist);
        // 生成一个校验码
        $code = $this->generateCode($m->account, $whitelist);

        $this->setAccountSrid($m->account, $whitelist, $m->srid);
        // 获取玩家数据
        $accountInfo = $this->getAccountInfo($m);//需要用到 m->serverWhere(initServerMap 初始化
        // 检测IP
        $accountInfo = $this->checkIP($accountInfo, $whitelist);
        // 渠道开关
        $channelStatus = $this->checkChannel($m->cid, $whitelist);
        $accountInfo['authCode'] = $code;
        $struct['accountInfo'] = $m->accountStruct($accountInfo, $whitelist, $channelStatus, $m->account);

        //账号加是渠道配置字段（重复则忽视 //保证没有配置时默认空
        foreach ($this->config_fields as $field){
            $config[$field] = $m->channelConfig[$field] ?? '';
        }
        $struct['accountInfo'] += $config ?? [];
        if ($m->channelInfo()) $struct['channelInfo'] = $m->channelInfo(); // 添加平台扩展参数


        // 获取最近登录区服列表(通过 cpid -> 大区,sid ,
        list($lastSid,) = $this->getLastLoginServers($m->account, $m->cpid,$m);
        $this->beforeSrid();
        if(!$lastSid){
            // 获取账号记录的区服数据 否则随机
            $server = $this->getServerInfo($accountInfo,CID);
        }else{
            $server = $m->serverStruct(
                $this->model('server')->getServerBySid($lastSid['sid']),
                $this->loginModel->actorStruct($accountInfo)
            );
        }


        $struct['serverInfo'] = $server;
        if(APP_DEV){
            $this->logEnd(json_encode($struct), 'login return data');
        }
        //$m->redis->lpush('report_dau',http_build_query(['login_dt'=>date('Y-m-d H:i:s'),'cid'=>CID] + $accountInfo));
        $this->logEnd($m->account, 'login success');
        $this->success($struct);
    }


    /**
     * 服务器列表
     */
    public function serverlist()
    {
        $ccid = $this->get('channel');
        $cpid = $this->get('gameId');
        // 检测设备码
        $channelStatus = $this->checkChannel();
        if (!$channelStatus) {
            $this->success([
                'last' => [],
                'servers' => [],
                'groups' => [],
            ]);
        }

        // 获取最近登录区服列表
        list($last, $accountInfo) = $this->getLastLoginServers($this->get('openId'), $cpid);

        // 把玩家最近登录列表结合到区服列表
        list($sgids, $servers) = $this->getServers($accountInfo, $cpid);

        // 获取区服组的数据
        $groups = $this->model('Server')->getServerGroups($sgids);

        $this->success([
            'last' => $last,
            'servers' => $servers,
            'groups' => $groups,
        ]);

    }

    public function loginServer()
    {
        $openId = $this->get('openId');
        $sid = $this->get('sid');
        $code = $this->checkServer($openId, $sid);
        if ($code !== false) {
            // 更新IP和登录时间
            $this->model('Account')->updateByAccount($openId, ['last_login_ip'=>ip()], $sid);
            $this->success(['authCode'=>$code]);
        }
        $this->error('服务器无效');

    }

    public function channelconfig()
    {
        $info = $this->getChannelPackageInfo();
        $this->success($info);
    }

    public function channelinfo()
    {
        $type = $this->get('type');
        $info = $this->getChannelPackageInfoByType($type);
        $this->success($info);
    }

    /**
     * 下载H5文件，只是内网测试用
     * @return void
     */
    public function h5download()
    {
        $filename = $this->get('file');
        $sid = intval($this->get('sid'));

        $filename = str_replace('..','',$filename);
        if (empty($filename))  exit('file param is empty.');
        if (!stripos($filename, '.')) $filename .= '.zip';
        if ($sid < 1)  $sid = 1;

        // 根据传过来的分服ID、配置名下载配置
        $filepath = 'upload/config/' . $sid . '/' . $filename;
        if (!file_exists($filepath)) $filepath = 'upload/config/' . 1 . '/' . $filename;
        header('location:http://10.31.1.6:91/'.$filepath. '?t='.time());
    }

    protected function redirect($url, $code = 302)
    {
        exit(curl($url));
    }

    protected function beforeSrid()
    {
    }
}